package me.hl.rxjava;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;

public class FluxDemo {

    private static Logger logger = LoggerFactory.getLogger(FluxDemo.class);


    @Test
    public void parallelTest() {
        Flux<Integer> a = Flux.range(0, 100).publishOn(Schedulers.parallel()).handle((i, sink) -> {
            sink.next(i);
        });


    }


    @Test
    public void sinkTest() {
        Flux.just(-1, 13, 9, 20, 30)
                .handle((i, sink) -> {
                    String letter = alphabet(i);
                    if (letter != null) {
                        sink.next(letter);
                    }
                }).subscribe(x -> logger.info("{}", x));


    }

    @Test
    public void onErrorReturn() {
        Flux.just(1).map(x -> danger()).onErrorReturn("error").subscribe(x -> logger.info(x));
    }


    public String danger() {
        throw new RuntimeException("haha");
    }

    public String alphabet(int letterNumber) {
        if (letterNumber < 1 || letterNumber > 26) {
            return null;
        }
        int letterIndexAscii = 'A' + letterNumber - 1;
        return "" + (char) letterIndexAscii;
    }

}
